package com.mashuai.utils.base;

import com.mashuai.utils.toolkit.achieve.MsExegesis;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @ClassName: MsEnvironmentUtils
 * @Description: 环境变量的工具类
 */
@MsExegesis("spring环境变量工具类")
@Component
public class MsEnvironmentUtils implements EnvironmentAware {
    //全局环境变量
    public static ConfigurableEnvironment environment;

    //存放当前项目环境下的所有配置文件的环境
    private static List<PropertySource<?>> propertySourceList = new CopyOnWriteArrayList<>();

    @Override
    public void setEnvironment(Environment env) {
        this.environment = (ConfigurableEnvironment) env;
    }


    /**
     * 获取指定key值
     */

    public static String getProperty(String key) {
        return environment.getProperty(key);
    }

    /**
     * 设置一个属性与值
     */

    public static void setProperty(String key, String value) {
        System.setProperty(key, value);
    }

    /**
     * 获取所有系统环境变量
     **/
    public static Map<String, Object> getSystemEnvironment() {
        Map<String, Object> systemEnvironment = environment.getSystemEnvironment();
        return systemEnvironment;
    }


    /**
     * 获取当前环境的所有配置文件属性值
     */

    public static List<PropertySource<?>> getAllPropertySources() throws Exception {
        if (propertySourceList.size() != 0) return propertySourceList;
        MutablePropertySources propertySources = environment.getPropertySources();
        for (Field field : propertySources.getClass().getDeclaredFields()) {
            if (field.getName().equals("propertySourceList")) {
                field.setAccessible(true);
                propertySourceList = (List<PropertySource<?>>) MsReflexUtils.getClassFieldVal(propertySources, "propertySourceList");
                break;
            }
        }
        return propertySourceList;
    }
}
